package com.cykj.runner;

import com.cykj.entity.CyGoodDO;
import com.cykj.mapper.GoodMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 王宇
 * @CreateTime: 2025-07-29  15:48
 * @BelongsProject: jd_seckill
 * @BelongsPackage: com.cykj.runner
 * @description 商品预热（启动时执行）
 */
@Component
public class DataWarmUpRunner implements ApplicationRunner {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private GoodMapper goodMapper;

    private List<CyGoodDO> goodList;

    @Override  // 启动时执行
    public void run(ApplicationArguments args) throws Exception {
        goodList = goodMapper.getGoodList();
        warmUpGood();
        warmUpStock();
    }

    private void warmUpGood() {
        // 循环商品列表
        for (CyGoodDO good : goodList) {
            // 获取商品id
            Integer goodId = good.getGoodId();
            // 根据前缀与id将该商品信息存入redis里
            String key = "good:" + goodId;
            redisTemplate.opsForValue().set(key, good);
        }
    }

    private void warmUpStock() {
        // 循环商品列表
        for (CyGoodDO good : goodList) {
            // 获取商品id
            Integer goodId = good.getGoodId();
            // 获取该商品库存
            Integer stock = good.getGoodStock();
            // 根据前缀与id将该商品库存信息存入redis里
            String key = "stock:" + goodId;
            redisTemplate.opsForValue().set(key, stock);
        }
    }
}
